package com.naizhuai.network.exception;

import android.content.Context;

import com.naizhuai.MainActivity;
import com.naizhuai.Model.AccountHelper;
import com.naizhuai.ui.user.login.LoginActivity;
import com.naizhuai.util.ActivityStackManager;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.IntentUtils;

/**
 * Created by lichenxi on 2017/5/18.
 */

public class ApiException extends Exception {
    private int code;
    private String displayMessage;

    public ApiException(Throwable throwable, int code) {
        super(throwable);
        this.code = code;
    }

    public static void showException(Throwable e, Context mContext) {
        showException(e, mContext, false);
    }

    public static void showException(Throwable e, Context mContext, boolean showDialog) {
        if (e instanceof ApiException) {
            ApiException ae = (ApiException) e;
            if (ae.getCode() == ServerException.USER_NO_LOGIN) {
                LoginActivity.exitLoginstart(mContext);
            }
            if (ae.getCode() == ServerException.USER_NOT_IN_COMPANY) {
                IntentUtils.startActivity(mContext, MainActivity.class);
//                ActivityStackManager.getInstance().killAllActivityExceptOne(MainActivity.class);
                MainActivity.updateUserData();
            } else {
                if (showDialog) {
                    DialogUtils.showPromptDialog(mContext, ae.getDisplayMessage());
                }
            }
        }
    }


    public static String showExceptionDetails(Throwable e) {
        if (e instanceof ApiException) {
            ApiException ae = (ApiException) e;
            return ae.getDisplayMessage();
        }else
            return e.getMessage();
    }

    public void setDisplayMessage(String displayMessage) {
        this.displayMessage = displayMessage;
    }

    public String getDisplayMessage() {
        return displayMessage;
    }

    public int getCode() {
        return code;
    }
}
